package com.greenbook.utils;

import java.util.Date;
import java.util.Map;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;
import com.greenbook.properties.JwtProperties;
import lombok.RequiredArgsConstructor;
import javax.crypto.SecretKey;

/**
 * JWT工具类，用于生成和验证JWT令牌
 */
@Component
@RequiredArgsConstructor
public class JwtUtil {
    /**
     * 创建JWT令牌
     *
     * @return JWT令牌字符串
     */
    public static String createToken(JwtProperties jwtProperties, Map<String, Object> claims) {
        // 证书签发时间
        Date now = new Date();
        // 证书过期时间
        Date expiration = new Date(now.getTime() + jwtProperties.getExpiration());
        // 生成密钥
        SecretKey key = Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes());
        return Jwts.builder()
                .claims(claims)  // 设置令牌载荷
                .issuedAt(now)  // 设置令牌签发时间
                .expiration(expiration)  // 设置令牌过期时间
                .signWith(key)  // 设置签名算法
                .compact();
    }

    /**
     * 验证并解析JWT令牌
     *
     * @param token
     * @return
     */
    public static Claims parseToken(JwtProperties jwtProperties, String token) {
        SecretKey key = Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes());
        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }
}
